<template>
  <div>
    <el-form
      style="width: 800px;"
      :model="innerData"
      :rules="rules"
      ref="ruleForm"
      label-width="130px"
    >
      <el-form-item label="会员套餐/期限" prop="xx">
        <div>
          <el-table
            class="small-table mb16"
            :data="innerData.memberConfig_list"
            border
            style="width: 100%"
          >
            <el-table-column prop="member_name" label="套餐名称">
            </el-table-column>
            <el-table-column label="套餐到期时间">
              <template slot-scope="scope">
                <p>
                  {{ scope.row.end_time | formatDate("yyyy-MM-dd hh:mm:ss") }}
                </p>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="del(scope.$index)"
                  ><i class="iconfont icon-del"></i>删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div>
            <el-button type="primary" size="medium" @click="openDlg('')"
              ><i class="iconfont icon-plus"></i>添加</el-button
            >
          </div>
        </div>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input
          class="w400"
          placeholder="请输入"
          v-model="innerData.user_name"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input
          class="w400"
          placeholder="请输入"
          v-model="innerData.mobilenum"
        ></el-input>
        <el-button type="primary" size="medium" class="ml16" @click="searchUser">搜索</el-button>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="innerData.sex">
          <el-radio label="1">男</el-radio>
          <el-radio label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="微信昵称">
        <el-input
          class="w400"
          placeholder="请输入"
          v-model="innerData.user_nickname"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input
          class="w400"
          placeholder="请输入"
          v-model="innerData.email"
        ></el-input>
      </el-form-item>
      <el-form-item label="地区">
        <el-select
          class="mr16"
          @change="getShiList"
          v-model="addressArr.sf"
          placeholder="全部"
          clearable
        >
          <el-option
            v-for="item in sfList"
            :key="item.district_id"
            :label="item.district"
            :value="item.district_id"
          ></el-option>
        </el-select>
        <el-select
          class="mr16"
          @change="getXianList"
          v-model="addressArr.shi"
          placeholder="全部"
          clearable
        >
          <el-option
            v-for="item in shiList"
            :key="item.district_id"
            :label="item.district"
            :value="item.district_id"
          ></el-option>
        </el-select>
        <el-select v-model="addressArr.xian" placeholder="全部" clearable>
          <el-option
            v-for="item in xianList"
            :key="item.district_id"
            :label="item.district"
            :value="item.district_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input placeholder="请输入" v-model="innerData.address"></el-input>
      </el-form-item>
      <el-form-item label="推荐人">
        <el-input
          class="w400"
          v-if="innerData.user_id && innerData.tj_mobilenum && this.$route.query.id"
          :disabled="!!innerData.user_id"
          placeholder="请输入"
          :value="innerData.tj_mobilenum"
        ></el-input>
        <el-select
          v-else
          v-model="innerData.tj_mobilenum"
          filterable
          remote
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in userList"
            :key="item.user_id"
            :label="item.user_name"
            :value="item.mobilenum"
          >
          </el-option>
        </el-select>
        <!-- <el-input
          class="w400"
          placeholder="请输入"
          v-model="innerData.coupon_name"
        ></el-input> -->
        <!-- <el-button class="ml16" type="primary" size="medium" >绑定</el-button> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrEdit">保存并返回</el-button>
        <el-button @click="back">返 回</el-button>
      </el-form-item>
    </el-form>

    <!-- // 添加编辑 -->
    <el-dialog title="添加套餐名称" :visible.sync="dialogFormVisible">
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        :rules="rules"
        label-width="130px"
      >
        <el-form-item label="等级" prop="member_id">
          <el-select
            v-model="dialogForm.member_id"
            placeholder="全部"
            clearable
          >
            <el-option
              v-for="item in comboList"
              :key="item.member_id"
              :label="item.member_name"
              :value="item.member_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐开始时间" prop="start_time">
          <el-date-picker
            v-model="dialogForm.start_time"
            value-format="timestamp"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
          <div class="label-tip">套餐默认时间为一年</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add2">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import memberComboAPI from "api/memberManagement/memberComboAPI";
import memberInfoAPI from "api/memberManagement/memberInfoAPI";
import { getDistrictList } from "api/lineManagement/lineCommodity";
import { mapState, mapMutations } from "vuex";

export default {
  computed: {
    ...mapState("middleData", ["memberInfoObj"]),
  },
  watch: {},
  data() {
    return {
      imgs: [],
      loading: false,
      rules: {
        member_id: [{ required: true, message: "请选择", trigger: "change" }],
        start_time: [{ required: true, message: "请选择", trigger: "change" }],
      },
      innerData: {
        memberConfig_list: [],
      },
      seriesList: [],
      dialogFormVisible: false,
      dialogForm: {},
      comboList: [],
      userList: [],
      addressArr: {
        sf: "",
        shi: "",
        xian: "",
      },
      sfList: [],
      shiList: [],
      xianList: [],
    };
  },
  methods: {
    ...mapMutations("middleData", ["setMemberInfoObj"]),
    // 获取会员套餐
    async getComboList() {
      memberComboAPI("getMemberConfigAllList").then((res) => {
        let arr = res.rData.concat([
          { member_id: "0", member_name: "所有人" },
          { member_id: "9999", member_name: "新用户" },
        ]);
        this.comboList = arr;
      });
    },
    del(index) {
      this.innerData.memberConfig_list.splice(index, 1);
    },
    async remoteMethod(query) {
      this.loading = true;
      let res = await memberInfoAPI("search", { query_value: query });
      this.userList = res.rData;
      this.loading = false;
    },
    async searchUser() {
      if(this.innerData.mobilenum) {
        let res = await memberInfoAPI('get', { query_value: this.innerData.mobilenum })
        // let res = await memberInfoAPI("search", { query_value: this.innerData.mobilenum });
        if(res.rData&&res.rData.length) {
          this.changeData(res.rData[0])
        }
      }  
    },
    // 获取省份
    async getSfList() {
      let res = await getDistrictList({ pid: "1" });
      this.sfList = res.rData;
    },
    async getShiList(val) {
      let res = await getDistrictList({ pid: val });
      this.shiList = res.rData;
    },
    async getXianList(val) {
      let res = await getDistrictList({ pid: val });
      this.xianList = res.rData;
    },
    openDlg() {
      this.dialogForm = {};
      this.dialogFormVisible = true;
    },
    async addOrEdit() {
      let data = { ...this.innerData };
      if (this.addressArr.sf && this.addressArr.shi && this.addressArr.xian) {
        let sf = this.sfList.find(
          (item) => item.district_id == this.addressArr.sf
        ).district;
        let shi = this.shiList.find(
          (item) => item.district_id == this.addressArr.shi
        ).district;
        let xian = this.xianList.find(
          (item) => item.district_id == this.addressArr.xian
        ).district;

        data.user_area = sf + "-" + shi + "-" + xian;
      }
      if (this.innerData.tj_mobilenum) {
        let user = this.userList.find(
          (item) => item.mobilenum === this.innerData.tj_mobilenum
        );
        data.tj_user_id = user.user_id;
      }
      if (this.innerData.user_id) {
        await memberInfoAPI("edit", data);
      } else {
        await memberInfoAPI("add", data);
      }
      this.$message.success("操作成功");
      this.back();
    },
    back() {
      this.$router.back();
    },
    // 整理数据返回的数据
    changeData(obj) {
      let data = { ...obj };
      data.sex += "";
      if (data.user_area) {
        let arr = data.user_area.split("-");
        console.log(arr);
        this.getSfList()
          .then(() => {
            let item = this.sfList.find((item) => item.district === arr[0]);
            return item;
          })
          .then((res) => {
            if (res) {
              this.addressArr.sf = res.district_id;
              return this.getShiList(res.district_id);
            }
          })
          .then(() => {
            let item = this.shiList.find((item) => item.district === arr[1]);
            if (item) {
              this.addressArr.shi = item.district_id;
              return this.getXianList(item.district_id);
            }
          })
          .then(() => {
            let item = this.xianList.find((item) => item.district === arr[2]);
            this.addressArr.xian = item && item.district_id;
          });
      }
      this.innerData = { ...data };
    },
    async add2() {
      await this.$refs.dialogForm.validate();
      let item = this.comboList.find(
        (item) => item.member_id === this.dialogForm.member_id
      );
      // console.log(item)
      let { member_id, member_name, price } = item;
      let start_time = ~~(this.dialogForm.start_time / 1000);
      let newYear = new Date(this.dialogForm.start_time).getFullYear() + 1;
      let end_time = ~~(
        new Date(this.dialogForm.start_time).setFullYear(newYear) / 1000
      );
      let flag = this.innerData.memberConfig_list.some(
        (item) => item.member_id === member_id
      );
      if (flag) {
        //
        this.$message.error("不能选择相同的套餐");
        return;
      }
      this.innerData.memberConfig_list.push({
        start_time,
        end_time,
        member_id,
        member_name,
        price: price * 100,
      });
      this.dialogFormVisible = false;
    },
  },
  created() {
    this.getComboList();
    this.getSfList();
    if (this.$route.query.id) {
      this.changeData(this.memberInfoObj);
      if (Object.keys(this.memberInfoObj).length == 0) {
        this.back();
      }
    }
  },
  beforeDestroy() {
    this.setMemberInfoObj({});
  },
};
</script>

<style lang="scss" scoped>
.w400 {
  width: 400px;
}
.bot {
  display: flex;
  justify-content: flex-end;
}
</style>
